$(function ($) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    //取消页面默认右键事件
    $(document).on('contextmenu',()=>{
        return false;
    });
    $('.chat-list li').each(function(){
        $(this).data('sort')==1?$(this).addClass('top'):$(this).removeClass('top');
    });
    if(localStorage.num){
        localStorage.clear();
    }
    let $chat_bg=$('.chat-bg'),
        $chat_wrap = $('.chat-wrap');
    let rs={
        room_more_taggle:true,
        $oEditnotice:$('span.edit-notice'),
        $oMore:$('#room-setting-more'),
        $oRename:$('input.rename-title'),
        $oOut:$('div.out'),
        Plus:'#plus',
        Reduce:'#reduce',
    };
    let doms={
        $oTitle:$('.chat-wrap .header .name'),
        $oCon:$('#info-content'),
        $oNavBox:$('#nav-box')
    };
    let set_focus=el=>{
        el=el[0];
        el.focus();
        let range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        let sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    };
    let send=(txt,roomId)=>{
        if (txt.length > 0 && txt != "") {
            let $oLi = doms.$oCon.children('li');
            if($oLi.length===0){
                $('.empty-info').hide();
            }
            $.ajax({
                type: "post",
                url: "home/send",
                data: {'txt': txt,roomId:roomId},
                success: function (data){
                    let args ={rId:roomId,dlgId:data.id,user:data.user,txt:txt,role:'ask'};
                    dialoge(args);
                    scrolltToBottom();
                },
                error: function (data) {
                    console.log(data.responseJSON.errors);
                }
            });
            $('.txt-box #textarea').text('');
        }
    };
    let scrolltToBottom=()=>{
        let scrollTop = doms.$oCon[0].scrollHeight;
        doms.$oCon.scrollTop(scrollTop);
    };
    let dialoge=({...args,$el=$('#info-content')})=>{
        console.log(args);
        const html = `<li class="dialogue ${args.role}" data-id="${args.dlgId}">
                            <img data-id="${args.user.id}" class="head-pic" src="${args.user.url}" title="点击查看用户信息"><em></em>
                            <div class="txt" data-self="${args.user.id}" data-id="${args.dlgId}">${args.txt}</div>
                            <span class="time">${args.user.time}</span>
                        </li>`,
            $oRoom = $(`.chat-side li.choose[data-id=${args.rId}]`),
            $oSession = $('#sessionStorage');
        $oRoom.children('div.info').children('span.con').html(args.txt);
        $oRoom.children('div.time').children('time').text(args.time);
        $oSession.length>0?$oSession.append(html):$el.append(html);
        sessionStorage[args.rId]?sessionStorage[args.rId]+=html:sessionStorage[args.rId]=html;
    };
    let dropload=(keyword,roomId)=>{
        const $his = $("#info-history");
        $("#info-history ul").children().remove();
        let [page,size]=[0,10];
        $his.dropload({
            distance:10,//拉动距离
            threshold : 10,
            domDown:{
                domClass   : 'dropload-down',
                domRefresh : '<p class="dropload-refresh">查看更多</p>',
                domLoad    : '<p class="dropload-load"><span class="loading"></span>加载中...</p>',
                domNoData  : '<p class="dropload-noData">暂无更多</p>'
            },
            loadDownFn : function(me){
                page++;
                getHistory(keyword,me,page,size,roomId);
            }
        });
    };
    let getHistory=(keyword,me,page,size,roomId)=>{
        let html = '',
            $info_his = $('#info-history ul');
        $.post('home/getHistory',{txt:keyword,page:page,size:size,roomId:roomId},function (data){
            let res = data.dialogue;
            if(res.length>0){
                res.forEach(v=>{
                    html+=`<li class="dialogue ans" data-id="${v.id}">
                                            <img data-id="${v.user_id}" class="head-pic" src="${v.url}" title="点击查看用户信息">
                                            <div class="info">
                                                <div class="right-t">
                                                    <span class="his-name">${v.user_name}</span>
                                                    <span class="his-time">${v.time}</span>
                                                </div>
                                                <div data-type="his" class="txt" data-self="${v.self}" data-id="${v.id}">${v.txt}</div>
                                            </div>
                                        </li>`;
                });
            }else{
                me.lock();// 无数据
                me.noData();
                me.resetload();
            }
            // 插入数据到页面，放到最后面
            $info_his.append(html);
            // 每次数据插入，必须重置
            me.resetload();
        });
    };
    doms.$oNavBox.click(e=>{
        const $oEm =$('#emotion');
        if(e.offsetX>120&&e.offsetX<136&&e.offsetY>8&&e.offsetY<26){
            $('#history').show();
            let keyword=$('#his-search').val().toString().trim();
            $(".dropload-down").remove();
            let roomId = $('li.choose').data('id');
            dropload(keyword,roomId);
        }
        if(e.offsetX>21&&e.offsetX<38&&e.offsetY>8&&e.offsetY<26){
            $oEm.show().css({
                left:e.pageX,
                top:e.pageY-280,
            });
            $(document).one("click", function(e){
                $oEm.hide();
            });
            e.stopPropagation();
        }
    });
    rs.$oMore.click(function () {
        const $oRS = $('.room-setting');
        if(rs.room_more_taggle){
            $('.chat-wrap').css('border-right','none');
            $oRS.animate({
                'right':'-250px'
            },300);
        }else{
            $oRS.animate({
                'right':'0'
            },300);
        }
        rs.room_more_taggle=!rs.room_more_taggle;
    });
    $(document).on('click',rs.Plus,function () {
        let {id,type} = $(this).data();
        $('#addUser-wrap').Room({
            roomId:id,
            type:1,
            confirm:function (ids) {
                $.ajax({
                    type:'get',
                    data:{id:id,ids:ids,type:type},
                    url:'home/addUsers',
                    success:function (data) {
                        if(type==0){
                            let names = data.names.join(','),
                                html='';
                            $('#info-content').tips('label',{
                                txt:`你邀请了"${names}"加入了群聊`,
                            });
                            data.users.forEach(function (v) {
                                html+=`<li><img src="${v.url}" alt=""><span>${v.name}</span></li>`;
                            });
                            $('ul.room-users').append(html);
                        }else {
                            $('ul.chat-list').append(`<li data-id="${data.id}">
                                                <img src="${data.url}" alt="">
                                                <div class="info">
                                                    <span class="title">${data.name}</span>
                                                   <span class="con"></span>
                                               </div>
                                               <div class="time">
                                                   <time></time>
                                               </div>
                                           </li>`);
                            $('.chat-setting i.chat').click();
                            $(`.chat-side .chat-list li[data-id=${data.id}]`).click();
                        }
                    }
                });
            }
        })
    });
    $(document).on('click',rs.Reduce,function () {
        //TODO:Reduce
        let roomId = $(this).data('id');
        $('#addUser-wrap').Room({
            roomId:roomId,
            btn_confirm:{txt:'删除',class:'chat-btn-danger'},
            type:2,
            confirm:function (ids) {
                $('#info-tip').tips('tip',{
                    txt:`确定要删除群成员?`,
                    confirm_txt:'删除',
                    btn_cancel:true,
                    confirm:function () {
                        $.ajax({
                            type:'get',
                            data:{roomId:roomId,ids:ids},
                            url:'home/reduceUsers',
                            success:function (data) {
                                $('ul.room-users li').each(function () {
                                    ids.includes($(this).data('id'))&&$(this).remove();
                                });
                            }
                        });
                    }
                })
            }
        })
    });
    rs.$oRename.focus(function (){
        sessionStorage.oldTitle = $(this).val();
    });
    rs.$oRename.blur(function (){
        let roomId = $(this).data('id'),
            val = $(this).val();
        if(val!=sessionStorage.oldTitle){
            $.post("home/roomRename", {roomId:roomId,title:val},function(data){
                let txt = '你修改群名为 "'+val+'"';
                $(`.chat-list li[data-id=${roomId}] .title`).text(val);
                doms.$oTitle.text(val);
                doms.$oCon.tips('label',{txt:txt});
                scrolltToBottom();
            });
        }
    });
    rs.$oOut.click(function () {
        $(this).data();
    });
    rs.$oEditnotice.click(function(){
        const $that = $(this),
            $info_tip = $('#info-tip'),
            roomData=$that.data();
        $.post("home/getRoomMain", {roomId:roomData.id},data=>{
            if(roomData.main==1){
                $info_tip.tips('notice',{
                    title:'群公告',
                    user_info:{show:true,name:data.name,time:data.notice_time,pic:data.url},
                    textarea:{id:'t1',text:data.notice,textMax:40},
                    confirm_txt:'发布',
                    confirm:function (t) {
                        $info_tip.tips('tip',{
                            title:'群公告',
                            txt:'该公告会通知全部群成员,是否发布?',
                            btn_cancel:true,
                            confirm:function () {
                                $.post("home/editNotice", {roomId:roomData.id,notice:t},()=>{
                                    send('@所有人\n'+t,roomData.id);
                                    scrolltToBottom();
                                    $that.text(t);
                                });
                            }
                        });
                    }
                });
            }else{
                $info_tip.tips('notice',{
                    title:'群公告',
                    user_info:{show:true,name:data.name,time:data.notice_time,pic:data.url},
                    textarea:{text:data.notice,textMax:40},
                    btn_disable:true,
                });
            }
        });
    });
    Echo.channel(`withDrawal`)
        .listen('WithDrawal',(e)=>{
            let $dialogue= $(`#info-content li.dialogue[data-id='${e.dialogueId}']`),
                tip = `<div class="withDrawal-tip"><span>${e.user.name} 撤回了一条消息</span></div>`,
                index = parseInt($dialogue.index());
            if(sessionStorage[index])sessionStorage[index]=tip;
            $dialogue.after(tip);
            $dialogue.remove();
            scrolltToBottom();
        });
    //room Setting
    $('.edit-notice,.rename-title').hover(function () {
        $(this).parent().children('em').show();
    },function () {
        $(this).parent().children('em').hide();
    });
    !(function($,window,undefined){
        let tips = function(el, options){
            this.$el = el,
                this.defaults = {
                    title:'提示',
                    txt:'发送时间超过2分钟的消息，不能被撤回。',
                    textarea:{id:null,text:'',textMax:16},
                    user_info:{show:false,pic:'',name:'',time:''},
                    oConfirm:el.children('#confirm'),
                    oCancel:el.children("#tip-close"),
                    confirm:confirm,
                    cancel:cancel,
                    btn_cancel:false,
                    confirm_txt:'确定',
                    btn_disable:false,
                },
            this.opts = $.extend({}, this.defaults, options||{});
        };
        let cancel = function(){
            this.oCancel.parent().hide();
        },
            confirm = function(){
            this.oConfirm.parent().hide();
        };
        tips.prototype = {
            init:function (){
                let {opts,$el} = this,
                    $oTitle = $el.children('.title'),
                    $oBtnCancel = $el.children('#cancel'),
                    $oConfirm = $el.children('#confirm'),
                    $oInfo = $el.children('.notice-user-info'),
                    $oCancel = $el.children("#tip-close,#cancel");
                $oTitle.text(opts.title);
                $oConfirm.text(opts.confirm_txt);
                opts.user_info.show?$oInfo.show():$oInfo.hide();
                opts.btn_cancel?$oBtnCancel.show()&&$oConfirm.removeClass('btn-center'):$oBtnCancel.hide()&&$oConfirm.addClass('btn-center');
                $oCancel.click(function () {
                    opts.cancel();
                });
                $oConfirm.unbind('click').click(function () {
                    $el.hide();
                    opts.confirm($(`textarea#${opts.textarea.id}`).val());
                });
                return $el.show();
            },
            tip:function (){
                let opts = this.opts,
                    $oCon = this.$el.children('.con');
                $oCon.html(`<span class="tip">${opts.txt}</span>`);
            },
            rename:function (){
                let opts = this.opts,
                    $oCon = this.$el.children('.con');
                $oCon.html(`<textarea id="${opts.textarea.id}" class="rename" maxlength="${opts.textarea.textMax}">${opts.textarea.text}</textarea>`);
                $(`textarea#${opts.textarea.id}`).attr('disabled',opts.btn_disable).focus();
            },
            notice:function (){
                let {opts,$el} = this,
                    $oCon = $el.children('.con'),
                    $oConfirm = $el.children('#confirm'),
                    $oInfo = $el.children('.notice-user-info'),
                    textarea = '<textarea id="'+opts.textarea.id+'" class="edit-notice" maxlength="'+opts.textarea.textMax+'">'+opts.textarea.text+'</textarea>';
                $oInfo.children('img').attr('src',opts.user_info.pic);
                $oInfo.children('span.info').html(opts.user_info.name+'<br>'+opts.user_info.time);
                opts.btn_disable&&($oConfirm.remove(),$oCon.after('<span class="inline-word">仅群主可编辑</span>'));
                $oCon.html(textarea);
                $('textarea#'+opts.textarea.id).attr('disabled',opts.btn_disable).focus();
            },
            label:function (){
                let opts = this.opts;
                this.$el.append(`<div class="withDrawal-tip"><span>${opts.txt}</span></div>`);
                scrolltToBottom();
                return this.$el;
            }
        };
        $.fn.tips = function(method,options){
            let tip = new tips(this,options);
            //eval('tip.'+method+'()');
            if(method!='label') tip.init();
            return tip[method]();
        }
    })(jQuery,window,undefined);
    /*begin addRoom*/
    !(function ($,window,document,undefined) {
        let Room = function(el, options){
                this.$el = el,
                this.$Close = el.children('.close-wrap,.cancel'),
                this.$Confirm = el.children('button#newRoom'),
                this.$from = el.children('.from-con').children('ul.from-list'),
                this.$to = el.children('.to-con').children('ul.to-list'),
                this.$tips = el.children('.to-con').children('span.tips'),
                this.defaults = {
                    oConfirm:$('button#newRoom'),
                    btn_confirm:{txt:'确定',class:'chat-btn-green'},
                    roomId:null,
                    type:0,
                    confirm:confirm,
                },
                this.opts = $.extend({}, this.defaults, options||{});
        };
        let confirm = function(){
                this.oConfirm.parent().hide();
            };
        Room.prototype = {
            init:function (){
                let {opts,$el,$Close,$Confirm,$from,$to,$tips} = this;
                $from.html('');
                $.get(`home/userList`,{id:opts.roomId,type:opts.type},function(data){
                        let html = '';
                        $.each(data,(i,v)=>{
                            html+=`<span class="letter">${i}</span>`;
                            $.each(v,(i,v)=>{
                                html+=`<div class="checkbox" data-id="${v.id}"><label>
                                        <li class="li-list" data-id="${v.id}">
                                        <img src="${v.url}" alt="">
                                        <span>${v.name}</span>
                                        <i class="cancel iconfont icon-jiaochacross78"></i>
                                        </li>
                                        <input data-id="${v.id}" class="check-item" type="checkbox" value="${v.id}">
                                        </label>
                                        </div>`;
                            });
                        });
                    $from.html(html);
                });
                $Confirm.removeClass().addClass('chat-btn').addClass(opts.btn_confirm.class).text(opts.btn_confirm.txt);
                $el.show();
                $Close.click(function () {
                    $el.hide();
                    $to.html('');
                });
                $Confirm.unbind('click').click(function () {
                    let ids= [];
                    $to.children('li.li-list').each((i,v)=>{
                        ids.push(parseInt($(v).data('id')));
                    });
                    $el.hide();
                    opts.confirm(ids);
                    $to.html('');
                });
                $(document).unbind('change').on('change',`#${$el.attr('id')} .check-item:checkbox`,function(){
                    let html = $(this).prev('li.li-list')[0].outerHTML,
                        id = $(this).prev('li.li-list').data('id'),
                        num = $(`#${$el.attr('id')} input.check-item:checked`).length;
                    num===0?$tips.html('请勾选需要添加的联系人')&&$Confirm.prop('disabled',true):$tips.html(`已选择了${num}个联系人`)&&$Confirm.prop('disabled',false);
                    $(this).is(':checked')?$to.append(html):$to.children(`li[data-id=${id}]`).remove();
                });
            },
        };
        $.fn.Room = function(options){
            let room = new Room(this,options);
            return room.init();
            //return tip[method]();
        }
    })(jQuery,window,document,undefined);

    $(document).on('click','.to-list li.li-list i.cancel',function () {
        let id = $(this).parent().data('id');
        $(this).parent().remove();
        $(`.check-item:checkbox[data-id=${id}]`).prop('checked',false);
    });
    $('.add-user').click(function () {
        $('#addUser-wrap').Room({
            confirm:function (ids) {
                $.ajax({
                    type:'get',
                    data:{ids:ids},
                    url:'home/createRoom',
                    success:function (data) {
                        const endFunc=()=>{
                            $('.chat-setting i.chat').click();
                            $(`.chat-side .chat-list li[data-id=${data.room.id}]`).click();
                        };
                        if(data.flag){
                            let room = data.room;
                            $('ul.chat-list').append(`<li data-id="${room.id}">
                                                <img src="${room.url}" alt="">
                                                <div class="info">
                                                    <span class="title">${room.name}</span>
                                                   <span class="con"></span>
                                               </div>
                                               <div class="time">
                                                   <time></time>
                                               </div>
                                           </li>`);
                            endFunc();
                        }else{
                            endFunc();
                        }
                    }
                });
            },
        });
    });
    /*end addRoom*/
    /*side choose*/
    let sc = {
        $oChat:$('.chat-setting i.chat'),
        $oAdr:$('.chat-setting i.address-list'),
        $oCole:$('.chat-setting i.collection'),
        $user_list:$('.chat-side ul.user-list'),
        $chat_list:$('.chat-side ul.chat-list'),
    };
    sc.$oChat.click(function () {
        if($('li.choose').length>0){
            $chat_bg.hide();
            $chat_wrap.show();
        }
        sc.$user_list.hide();
        sc.$chat_list.show();
    });
    sc.$oAdr.unbind('click').click(function () {
        $chat_bg.show();
        $chat_wrap.hide();
        sc.$user_list.show();
        sc.$chat_list.hide();

        $.ajax({
            type:'get',
            url:'home/userList',
            success:function (data) {
                let html = '';
                $.each(data,function (i,v) {
                    html+=`<span class="letter">${i}</span>`;
                    $.each(v,(i,v)=>{
                        html+=`<li class="li-list" data-id="${v.id}">
                    <img src="${v.url}" alt="">
                    <span>${v.name}</span>
                    </li>`;
                    });
                });
                sc.$user_list.html(html);
            }
        });
    });
    sc.$oCole.click(function () {
        //TODO:收藏
        console.log('TODO:收藏')
    });
    $('.chat-setting i.iconfont').click(function () {
        $(this).addClass('bg-color').siblings('i').removeClass('bg-color');
        rs.room_more_taggle=true;
        $('.room-setting').animate({
            'right':'0'
        },300);
    });
    /*end side choose*/
    /*#textarea*/
    let tp={
        $textarea:$('div#textarea'),
        $btn_send:$('#send'),
    };
    tp.$textarea.keydown(function (e) {
        let keycode = window.event ? e.keyCode : e.which,
            txt = $(this).html().trim();
        if (keycode == 13 && e.ctrlKey) {
            txt += "\n";
            $(this).html(txt);
        }else if(keycode == 13) {
            e.preventDefault();
            send(txt,sessionStorage.roomId);
        }
    });
    tp.$btn_send.click(function () {
        let txt = tp.$textarea.html().trim();
        send(txt,sessionStorage.roomId);
    });
    $(document).on('click','#info-content .head-pic',function (e) {
        let id = $(this).data('id');
        $.ajax({
            type: "post",
            url: "home/getUserInfo",
            data: {'id': id},
            success: function (data) {
                let {name,email,url,sex}=data.user;
                $('.user-info .name').text(name);
                $('.user-info .count').text(email);
                $('.user-info .img-header').attr('src',url);
                $('.user-info .sex').attr('src',`images/chat/${sex}.png`)
            },
            error: function (data) {
                console.log(data.responseJSON.errors);
            }
        });
        $('.user-info').css({
            left:e.pageX,
            top:e.pageY,
        }).show();
    });
    $('.user-info').mouseleave(function () {
        $('.user-info').hide();
    });
    $(".dialoge-op").on("mousedown", function(e){
        e.stopPropagation();
    });
    $(".chat-list-op").on("mousedown", function(e){
        e.stopPropagation();
    });
    doms.$oNavBox.on("click", function(e){
        e.stopPropagation();
    });
    $('#emotion img').click(function () {
        let $img = $(this),
            $input_box = $('div#textarea');
        $input_box.append($img);
        set_focus($input_box);
    });
    /*his*/
    /*start history*/
    $('#history #his-close').click(function () {
        $(this).parent('#history').hide();
    });
    $('#history #his-search').on('input propertychange',function (e){
        let keyword=$('#his-search').val().toString().trim();
        $(".dropload-down").remove();
        let roomId = $('li.choose').data('id');
        dropload(keyword,roomId);
    });
    /*chat-list-op*/
    $(document).on('mousedown','.chat-list li',function(e) {
        if(3 == e.which){
            let roomId = $(this).data('id'),
                sort = $(this).data('sort'),
                per = $(this).data('per'),
                $this = $(this),
                $title_el = $(this).children('.info').children('span.title'),
                $con_el = $(this).children('.info').children('span.con'),
                $sort_el = $('.chat-list-op .sort'),
                $del_el = $('.chat-list-op .delete'),
                $rename_el = $('.chat-list-op .rename'),
                $ul_op = $('.chat-list-op');
            sort==0?$sort_el.text('置顶'):$sort_el.text('取消置顶');
            per==1?$rename_el.hide():$rename_el.show();
            $ul_op.show().css({
                left:e.pageX,
                top:e.pageY,
            });
            $(document).one("mousedown", function(e){
                $ul_op.hide();
            });
            e.stopPropagation();
            $sort_el.unbind('click').click($this,function () {
                let $chatList = $('.chat-list');
                $.post("home/roomSort", {roomId:roomId},function(data){
                    $ul_op.hide();
                    $this.data('sort',data);
                    if(data==1){
                        $this.hide().show().addClass('top');
                        $chatList.prepend($this);
                    }else{
                        $this.hide().show().removeClass('top');
                        $chatList.append($this);
                    }
                });
            });
            $del_el.unbind('click').click(function () {
                $.post("home/roomDelete", {roomId:roomId},function(data){
                    $ul_op.hide();
                    $(`.chat-list li[data-id=${roomId}]`).remove();
                });
            });
            $rename_el.unbind('click').click(function () {
                let title = $title_el.text(),
                    $infoCon= $('#info-content'),
                    $infoTip = $('#info-tip');
                $ul_op.hide();
                $infoTip.tips('rename',{
                    title:'修改群名称',
                    textarea:{id:'t2',text:title,textMax:16},
                    btn_cancel:true,
                    confirm:function (t) {
                        $.post("home/roomRename", {roomId:roomId,title:t},function(data){
                            $title_el.text(t);
                            let txt = `你修改群名为${t}`;
                            $con_el.text(txt);
                            if($this.hasClass("choose")){
                                $infoCon.tips('label',{txt:txt});
                                doms.$oTitle.text(t);
                                scrolltToBottom();
                            }
                        });
                    }
                });
            });
        }
    });

    /*room-list-op*/
    $(document).on('click','.chat-side .chat-list li',function () {
        let room_id = $(this).data('id'),
            $oTitle = $(this).children('div.info').children('span.title'),
            $oCon=$('#info-content');
        if($('li.choose').length==0){
            $chat_bg.hide();
            $chat_wrap.show();
        }
        doms.$oTitle.html($oTitle.text());
        sessionStorage.roomId&&Echo.leave(`chat.${sessionStorage.roomId}`);
        sessionStorage.roomId = parseInt(room_id);
        if($(this).hasClass('choose')){
            return false
        }else{
            Echo.join(`chat.${sessionStorage.roomId}`)
                .here((users) => {
                    console.log(users.length);
                })
                .joining((user) => {
                    if($('li.choose').data('id')==user.roomId){
                        $oCon.tips('label',{txt:user.name+' 加入房间'});
                        scrolltToBottom();
                    }
                })
                .leaving((user) => {
                    if($('li.choose').data('id')==user.roomId) {
                        $oCon.tips('label',{txt:user.name+' 离开房间'});
                        scrolltToBottom();
                    }
                })
                .listen('Event', (e) => {
                    let user=Object.assign(e.user,{time:e.time,url:e.url}),
                        id = $('li.choose').data('id'),
                        args ={rId:e.roomId,dlgId:e.dialogueId,user:user,txt:e.txt,role:'ans'};
                    if(args.dlgId<0){
                        if(args.dlgId===-1){
                            $oCon.tips('label',{txt:`${user.name}修改了群名为 "${args.txt}"`});
                            $(`.chat-list li[data-id=${args.rId}] .info span.title`).text(args.txt);
                            id==args.rId&&doms.$oTitle.text(args.txt);
                        }else if(args.dlgId===-2){
                            $oCon.tips('label',{txt:`${args.user.name}邀请"${args.txt.join(',')}"加入群聊`});
                            //TODO:console.log(args.txt[0].includes(3))
                        }else if(args.dlgId===-3){
                            $oCon.tips('label',{txt:`"${args.user.name}"退出群聊`});
                        }
                    }else {
                        dialoge(args);
                    }
                    scrolltToBottom();
                });
            $.ajax({
                type:'get',
                url:`home/chatList/${room_id}`,
                success:function (data) {
                    if(data.list){
                        let html = '';
                        data.list.forEach((v)=>{
                            html+=`<li class="dialogue ${v.role}" data-id="${v.id}">
                                <img data-id="${v.user_id}" class="head-pic" src="${v.url}" title="点击查看用户信息">
                                <em></em>
                                <div class="txt" data-self="${v.user_id}" data-id="${v.id}">${v.txt}
                                </div>
                                <span class="time">${v.time}</span>
                                 </li>`;
                        });
                        doms.$oCon.html(html);
                        scrolltToBottom();
                    }
                    let $oUl =$('ul.room-users'),
                        $oIn = $('.room-op input.rename-title'),
                        $oSpan = $('.room-op span.edit-notice'),
                        $oGroups = $('.room-op div.group-op'),
                        $oOut = $('.room-setting .out'),
                        add = `<li class="add"><div data-id="${room_id}" data-type="${data.room.type}"  id="plus">＋</div><span>添加</span></li>`,
                        del = `<li class="delete"><div data-id="${room_id}" id="reduce">－</div><span>删除</span></li>`;
                    if(data.users!=0){
                        let html = data.isMain==1?add+del:add;
                        data.users.forEach((v)=>{
                            html+=`<li data-id="${v.id}"><img src="${v.url}" alt=""><span>${v.name}</span></li>`;
                        });
                        $oUl.html(html);
                        $oGroups.show();
                        $oOut.show();
                        data.room.name != '群聊'?($oIn.val(data.room.name)):$oIn.val('');
                        $oIn.data('id',room_id);
                        $oSpan.data('main',data.isMain);
                        $oSpan.data('id',room_id);
                        $oOut.data('main',data.isMain);
                        data.isMain==0?$oOut.text('退出群聊'):$oOut.text('删除并退出');
                        data.isMain==0&&data.room.notice===null&&$oSpan.unbind('click');
                        $oSpan.text(data.room.notice===null?(data.isMain==1?'点击编辑群公告':'暂无群公告'):`@所有人 ${data.room.notice}`);
                    }else{
                        let html = `${add}<li><img src="${data.user.url}" alt=""><span>${data.user.name}</span></li>`;
                        $oUl.html(html);
                        $oGroups.hide();
                        $oOut.hide();
                    }
                    $oOut.data('id',room_id);
                }
            });
        }
        $(this).addClass('choose').siblings().removeClass('choose');
        let roomId = $('li.choose').data('id'),$ss = $('#sessionStorage');
        typeof sessionStorage[roomId] ==='undefined'?$ss.html(''):$ss.html(sessionStorage[roomId]);
    });

    /*dialogue-op*/
    $(document).on('mousedown','.dialogue .txt',function(e) {
        if (3 === e.which){
            let $this = $(this),
                $oCon = $this.parents('#info-content'),
                $oHis = $this.parents('#info-history'),
                $dialogue = $this.parent('li.dialogue'),
                $d_op=$('.dialoge-op'),
                $oWithdrawal=$d_op.children('.withdrawal'),
                $oClear = $d_op.children('.clear'),
                $oDelete = $d_op.children('.delete'),
                id = parseInt($this.data('id')),
                self = parseInt($this.data('self'));
            $dialogue.hasClass('ask')&&$oCon.length>0?($oWithdrawal.show(),$oClear.show()):($oWithdrawal.hide(),$oClear.hide());
            $oHis.length>0&&(1===self?$oDelete.show():$oDelete.hide());
            $d_op.show().css({
                left:e.pageX,
                top:e.pageY,
            });
            $(document).one("mousedown", function(e){
                $d_op.hide();
            });
            e.stopPropagation();
            //删除
            $oDelete.unbind('click').click($this,function(){
                $d_op.hide();
                let isSoftDel = typeof $this.data('type')==='undefined'?1:0;
                let index = parseInt($dialogue.index());
                $.post("home/deleteDialogue", {id:id,isSoftDel:isSoftDel},function(){
                    $this.parent('li.dialogue').remove();
                    if(isSoftDel==0)$(`li.dialogue[data-id=${id}]`).remove();

                });
            });
            //撤回
            $oWithdrawal.unbind('click').click($this,function (e) {
                let index = parseInt($dialogue.index());
                $d_op.hide();
                $.post("home/withdrawal", {id:id},function(data){
                    if(data.flag){
                        $dialogue.after('<div class="withDrawal-tip"><span>你撤回了一条消息</span></div>');
                        $dialogue.remove();
                    }else {
                        $('#info-tip').tips('tip');
                    }
                });
            });
            //清屏
            $oClear.unbind('click').click(function (e) {
                $d_op.hide();
                $oCon.children().remove();
                let roomId = $('.chat-side li.choose').data('id');
                if(sessionStorage[roomId]){
                    sessionStorage.removeItem(roomId);
                }
            });
        }
    });
});